<template>
  <el-dialog title="新增角色" :close-on-click-modal="false" @close="close" :visible.sync="visible">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName">
        <el-input v-model="form.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" :label-width="formLabelWidth">
        <el-input v-model="form.roleCode"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
        <el-input v-model="form.roleDesc"></el-input>
      </el-form-item>
      <el-form-item label="权限管理" :label-width="formLabelWidth">
        <c-tree
          style="height: 300px;overflow: auto;"
          ref="resourceTree"
          check-strictly
          show-checkbox
          node-key="id"
          :default-expanded-keys="resourceDefault"
          :data="resourceTree"
          :props="resourceProps">
        </c-tree>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <c-button type="primary" @click="btnOk">确 定</c-button>
    </div>
  </el-dialog>
</template>

<script>
import Options from '@/constants/Options'

export default {
  name: 'SDialogAdd',
  props: {
    data: {
      type: Object,
      default () {
        return {
          resourceTree: []
        }
      }
    }
  },
  data () {
    return {
      formLabelWidth: '120px',
      visible: true,
      form: {
        roleName: '',
        roleCode: '',
        roleDesc: ''
      },
      rules: {
        roleName: this.$checkRules.roleNameR
      },
      resourceProps: {
        children: 'nodes',
        label: 'text'
      },
      resourceDefault: [Options.ResTreeRoot],
      resourceTree: this.data.resourceTree
    }
  },
  methods: {
    // 固定写法，每次加载都需要重置form
    close () {
      this.$emit('close')
    },
    btnOk (btn) {
      this.$refs['form'].validate((valid) => {
        // 校验通过
        if (valid) {
          this.form.resources = this.$refs['resourceTree'].getCheckedKeys()
          this.$service.system.addRole(this.form).then(() => {
            this.visible = false
            this.$emit('ok')
          }).finally(() => {
            btn.isLoading(false)
          })
        } else {
          btn.isLoading(false)
        }
      })
    }
  }
}
</script>

<style>

</style>
